import random

from django.contrib import admin
from django.utils.html import format_html

from mms.models import Media


# Register your models here.
class MediaAdmin(admin.ModelAdmin):
    # 设置媒体文件图标
    def image_tag(self, obj):
        if obj.media_icon:
            return format_html(f'<img src="{obj.media_icon.url}" style="width:64px;height:64px;"/>')
        return ''

    image_tag.allow_tags = True
    image_tag.short_description = '媒体图标'

    # 设置标签显示效果
    def get_queryset(self, request):
        return super().get_queryset(request).prefetch_related('media_tags')

    def tag_list(self, obj):
        color = ['#0B5ED7', '#6C757D', '#198754', '#BB2D3B', '#FFCA2C', '#31D2F2', '#212529']
        return format_html(''.join(
            f'<span style="color: #fff; background-color: {random.choice(color)}; border-color: #dc3545; display: inline; padding: .375rem .25rem; margin-top: .25rem; margin-left: .25rem; margin-bottom: .25rem; font-size: 0.6rem; font-weight: 300; line-height: 0.6; text-align: center; vertical-align: middle; border: 1px solid transparent; border-radius: .25rem;">{o.name}</span>'
            for o in obj.media_tags.all()))

    tag_list.allow_tags = True
    tag_list.short_description = '标签'

    # 显示字段
    list_display = ['image_tag', 'media_name', 'media_size', 'media_type', 'media_category', 'course_category',
                    'course_time', 'course_teachers', 'course_start_time', 'tag_list', 'media_remark', 'media_creator',
                    'media_creation_time', 'media_modification_time', 'last_editor']
    # 隐藏字段
    exclude = ['media_size', 'media_creator', 'media_creation_time', 'media_modification_time', 'last_editor']
    # 查询字段
    search_fields = ['media_name', 'media_type', 'media_category', 'course_category', 'media_tags__name',
                     'course_teachers']
    # 直接编辑字段
    list_editable = ['media_type', 'media_remark', 'media_category', 'course_category', 'course_time',
                     'course_teachers', 'course_start_time']
    # 字段分组
    fieldsets = [
        ('基础信息', {'fields': ['media_icon', 'media_file', 'media_name']}),
        ('媒体类别', {'fields': ['media_type', 'media_category', 'course_category']}),
        ('课件信息', {'fields': ['course_time', 'course_teachers', 'course_start_time']}),
        ('其他信息', {'fields': ['media_tags', 'media_remark']}),
    ]

    def save_model(self, request, obj, form, change):
        # 设置媒体文件创建者
        if not obj.media_creator:
            obj.media_creator = request.user
        obj.last_editor = request.user.username
        # 设置媒体文件名称
        if not obj.media_name:
            obj.media_name = obj.media_file.name
        # 设置媒体文件大小
        if not obj.media_size:
            obj.media_size = obj.filesize
        super().save_model(request, obj, form, change)


admin.site.register(Media, MediaAdmin)
